package org.ns.longhttp.selector.requestmapper;

import io.netty.buffer.ByteBuf;
import org.ns.longhttp.wrapper.GetRequestWrapper;

import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

public class MappingQueueEntry {

    private String key;
    private LinkedHashSet<QueueEntryWrapper> queue = new LinkedHashSet<>();
    private AtomicLong dataIndexs = new AtomicLong();

    public void add (GetRequestWrapper requestWrapper, int second) {
        synchronized (queue) {
            long invalidTime = System.currentTimeMillis() + second * 1000;
            QueueEntryWrapper queueEntryWrapper = new QueueEntryWrapper(requestWrapper, invalidTime);
            queue.add(queueEntryWrapper);
        }
    }

    public MappingQueueEntry(String key) {
        this.key = key;
    }


    public void closeInvalid() {
        synchronized (queue) {
            Iterator<QueueEntryWrapper> iterator = queue.iterator();
            while (iterator.hasNext()) {
                QueueEntryWrapper next = iterator.next();
                if (next.isInvalid()) {
                    iterator.remove();
                    next.close();
                }
            }
        }
    }

    public List<GetRequestWrapper> getRequestWrappers() {
        synchronized (queue) {
            List<GetRequestWrapper> requestWrappers = new ArrayList<>();
            Iterator<QueueEntryWrapper> iterator = queue.iterator();
            while (iterator.hasNext()) {
                QueueEntryWrapper next = iterator.next();
                iterator.remove();
                if (next.isInvalid()) {
                    next.close();
                } else {
                    requestWrappers.add(next.getRequestWrapper());
                }
            }
            return requestWrappers;
        }
    }

    public void writeAll(ByteBuf content, String contentType) {

        synchronized (queue) {
            Iterator<QueueEntryWrapper> iterator = queue.iterator();
            while (iterator.hasNext()) {
                QueueEntryWrapper next = iterator.next();
                if (next.isInvalid()) {
                    next.close();
                } else {
                    next.getRequestWrapper().write(content, contentType);
                }
                iterator.remove();
            }
        }
    }
    public boolean write(ByteBuf content, String contentType) {
        synchronized (queue) {
            Iterator<QueueEntryWrapper> iterator = queue.iterator();
            while (iterator.hasNext()) {
                QueueEntryWrapper next = iterator.next();
                iterator.remove();
                if (next.isInvalid()) {
                    next.close();
                } else {
                    next.getRequestWrapper().write(content, contentType);
                    return true;
                }
            }
            return false;
        }
    }


}
